package com.epam.xml.xmlimport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.epam.xml.bank.Account;
import com.epam.xml.bank.Card;
import com.epam.xml.bank.Client;

public class DOMParser {
	private Client currentClient;
	private Account currentAccount;
	private Card card;
	private String currency;
	private int amount;

	public List<Client> parse(Element root) throws SAXException, IOException {
		List<Client> clients = new ArrayList<Client>();
		NodeList clientNodes = root.getElementsByTagName("p:client");
		for (int i = 0; i < clientNodes.getLength(); i++) {
			currentClient = new Client();
			Element clientElement = (Element) clientNodes.item(i);
			currentClient.setLogin(clientElement.getAttribute("login"));
			currentClient.setPassword(clientElement.getAttribute("password"));
			currentClient.setId(Integer.valueOf(getBabyValue(clientElement,
					"p1:id")));
			currentClient.setName(getBabyValue(clientElement, "p1:name"));

			Element accountElements = getBaby(clientElement, "p1:accounts");
			NodeList accountNodes = accountElements
					.getElementsByTagName("p1:account");
			for (int j = 0; j < accountNodes.getLength(); j++) {
				Element currentAccountElement =(Element)accountNodes.item(j);
				currentAccount = new Account();
				currentAccount.setId(Integer.valueOf(getBabyValue(
						currentAccountElement, "p2:id")));
				currency = getBabyValue(currentAccountElement, "p3:currency");
				amount = Integer.valueOf(getBabyValue(currentAccountElement,
						"p3:amount"));
				HashMap<String, Integer> currencyAndAmount = new HashMap<String, Integer>();
				currencyAndAmount.put(currency, amount);
				card = new Card();
				card.setCardType(getBabyValue(currentAccountElement,
						"p5:cardType"));
				card.setNumber(getBabyValue(currentAccountElement, "p5:number"));
				card.setPin(getBabyValue(currentAccountElement, "p5:pin"));
				currentAccount.setCard(card);
				currentAccount.setCurrencyAndAmount(currencyAndAmount);
				currentClient.addAccount(currentAccount);
			}
			
			clients.add(currentClient);
		}
		return clients;
	}

	private static Element getBaby(Element parent, String childName) {
		NodeList nlist = parent.getElementsByTagName(childName);
		Element child = (Element) nlist.item(0);
		return child;
	}

	private static String getBabyValue(Element parent, String childName) {
		Element child = getBaby(parent, childName);
		Node node = child.getFirstChild();
		String value = node.getNodeValue();
		return value;
	}

}
